package com.eternal.control;

import android.annotation.SuppressLint;
import android.app.Application;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.annotation.NonNull;

import com.eternal.base.concat.DeviceInfo;
import com.eternal.base.concat.DeviceMinModel;
import com.eternal.base.concat.DeviceModel;
import com.eternal.base.data.DeviceRepository;
import com.eternal.base.data.ble.BleStatue;
import com.eternal.base.global.ProgressEvent;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.component.BaseViewModel;
import com.eternal.framework.utils.KLog;
import com.eternal.framework.utils.RxUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ControlCModel extends BaseViewModel {
    public ControlCModel(@NonNull Application application) {
        super(application);
    }
    public DeviceModel info,lastInfo;
    public String mac;
    private byte port;
    public boolean refreshStopped;
    public boolean isRefreshComplete;

    public MutableLiveData<String> show=new MutableLiveData<>();
    public MutableLiveData<Boolean> controlTypeByHumModel =new MutableLiveData<>();

    private DeviceRepository repository;
    private Disposable refresh;

    @SuppressLint("CheckResult")
    public void init(final DeviceRepository repository, final String mac ,final byte port){
        this.repository=repository;
        this.mac=mac;
        this.port = port;
        repository.getModel(mac,port)
                .compose(RxUtils.<DeviceModel>bindToLifecycle(getLifecycleProvider()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if(repository.isConnect(mac)){
                            RxBus.getDefault().post(new ProgressEvent(ProgressEvent.START));
                        }
                    }
                })
                .subscribe(new Consumer<DeviceModel>() {
                    @Override
                    public void accept(DeviceModel model){
                        ControlCModel.this.info=model;
                        controlTypeByHumModel.setValue(model.isControlTypeByHum);
                        Messenger.getDefault().sendNoMsg(ControlCFragment.REFRESH);
                        if(repository.isConnect(mac)){
                            RxBus.getDefault().post(new ProgressEvent(ProgressEvent.END));
                        }
                        start();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        KLog.e(throwable);
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void sendData(){
        final BleStatue statue=repository.getConnect(mac);
        if(statue!=null){
            refreshStopped=false;
            repository.setCModel(statue, info)
                    .compose(RxUtils.<Boolean>bindToLifecycle(getLifecycleProvider()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            RxBus.getDefault().post(new ProgressEvent(ProgressEvent.END));
                            start();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
//                            throwable.printStackTrace();
                            KLog.e(throwable);
                        }
                    });

        }
    }

    public void cancelUpdate(){
        if(repository.isConnect(mac)){
            RxBus.getDefault().post(new ProgressEvent(ProgressEvent.START));
        }
        stop();
    }

    public void setControlTypeByHum(boolean isControlTypeByHum) {
        repository.setControlTypeByHum(mac, isControlTypeByHum)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .subscribeOn(Schedulers.io())
                .subscribe();
    }

    void start(){
        refreshStopped=false;
        BleStatue statue=repository.getConnect(mac);
        if (statue != null) {
            if (refresh == null) {
                refresh = repository.getCModel(statue).subscribe(new Consumer<DeviceModel>() {
                    @Override
                    public void accept(DeviceModel deviceModel) throws Exception {
                        if (deviceModel != null && info != null) {
                            lastInfo = info.clone();
                            deviceModel.isControlTypeByHum = info.isControlTypeByHum;
                            info = deviceModel;
                            Messenger.getDefault().sendNoMsg(ControlCFragment.REFRESH);
                            isRefreshComplete = true;
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        KLog.e(throwable);
                        isRefreshComplete = true;
                    }
                });
            }
        } else {
            isRefreshComplete = true;
        }
    }

    void stop(){
        if(refresh!=null){
            refresh.dispose();
            refresh=null;
        }
        refreshStopped=true;
    }

    public void save(){
        if(repository.isConnect(mac)){
            repository.saveModel(mac, (byte)0x0,info).subscribeOn(Schedulers.io()).subscribe();
        }
    }
}
